<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.*,com.cap.bts.crmdp.dealer.coupon.domain.Ticket,com.cap.bts.crmdp.dealer.meal.dto.ResultDto"
	pageEncoding="UTF-8"%>
<%
    ArrayList ticketList = (ArrayList) request
					.getAttribute("ticketList");

			ArrayList resultList = (ArrayList) request
					.getAttribute("resultList");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>套餐定义</title>
<%@include file="../include/include.jsp"%>
<link rel="stylesheet" type="text/css" href="${csspath }/public.css" />
<script type="text/javascript" src="${jspath}/jquery/jquery-1.8.3.js"></script>
<link rel="stylesheet" type="text/css"
	href="${bootstrapPath}/css/bootstrap.css" />
<script type="text/javascript" src="${bootstrapPath}/js/bootstrap.js"></script>
<script type="text/javascript"
	src="${bootstrapPath}/js/bootstrap3-validation.js"></script>
<script type="text/javascript" src="${layerPath}/layer.js"></script>
<script type="text/javascript" src="${jspath}/jquery/jquery.alerts.js"></script>
</head>

<script type="text/javascript">
	var row_count = 0;
	var giftCount = 0;
	$(function() {
		$("#mealForm").validation({
			icon : true
		});

		//返回
		$("#returnBtn").click(function() {
		
				$("#mealForm").attr('action','${webcontext}/crmdp/dealer/meal/getMealList');
				$("#mealForm").submit();
		});

		//自加行
		$("#insertRow")
				.click(
						function() {
							var table = $("#data_tabs");
							var row = $("<tr></tr>");
							var td0 = $("<td></td>");
							var td1 = $("<td></td>");
							var td2 = $("<td></td>");
							var td3 = $("<td></td>");
							var td4 = $("<td></td>");
							var td5 = $("<td></td>");
							td0.append($("<select id='shortName"+row_count+"' class='form-control input-sm' style='width:220px;' onchange='changeTicketType2(this[selectedIndex].value,this.id)'><option value='N/A'>--------请选择项目---------</option><core:forEach items='${ticketList}' var='list'><option value='${list.id}'>${list.ticketName}</option></core:forEach></select>"));
							row.append(td0);

							td1.append($("<input class='form-control input-sm' readonly id='ticketType"+row_count+"' type='text' />"));
							row.append(td1);
							
							td2.append($("<input class='form-control input-sm text-right' id='numberOfUse"+row_count+"' type='text' onchange='editPrepayAmount(this.id)'/>"));
							row.append(td2);
							
							td3.append($("<input class='form-control input-sm text-right' readonly id='onePrice"+row_count+"' type='text' value='0' />"));
					        row.append(td3);
					
							td4.append($("<input class='form-control input-sm text-right' readonly id='prepayAmount"+row_count+"' type='text' />"));
							row.append(td4);
							
							td5.append($("<button type='button' id='delete"
											+ row_count
											+ "' class='btn btn-warning btn-sm' onclick='deleteRow(this.id)' style='margin-left: 10px;'>删除</button> "));
							row.append(td5);

							table.append(row);
							row_count++;
							changeNumberOfUse();
							sumPrepayAmount();
						});

		//提交
		$("#saveBtn")
				.click(
						function() {
							if ($("#mealForm").valid(this, '内容出错') == false) {
								return false;
							}
							var validPeriod = $("#validPeriod").val();
							if(validPeriod == null || validPeriod==""){
								jAlert("有效期不能为空","提示");
								return false;
							}
							var memberBenfit = $("#memberBenfit").val();
							if(memberBenfit == null || memberBenfit==""){
								jAlert("会员福利不能为空","提示");
								return false;
							}
							
							var ticketDefId = $("#shortName").val();
							var shortName = $("#shortName option:selected").text();
							var numberOfUse = $("#numberOfUse").val();
							
							var dataStr="";
							if (ticketDefId != "N/A" && ticketDefId != undefined
									&& ticketDefId != null
									&& ticketDefId != "") {
								dataStr = ticketDefId+"@#"+shortName+"@#"+numberOfUse+"###";
							}
							if (row_count >= 1) {
								for ( var k = 0; k < row_count; k++) {
									var shortName = $("#shortName" + k).val();
									if (shortName != "N/A" && shortName != undefined
											&& shortName != null
											&& shortName != "") {
										var ticketDefId = $("#shortName" + k).val();
										var shortName = $("#shortName"+k+" option:selected").text();
										var numberOfUse = $("#numberOfUse" + k)
												.val();

										dataStr = dataStr + ticketDefId + "@#"+shortName+"@#"
												+ numberOfUse + "###";
									}
								}
							}
							
							//入会礼
							var giftName = $("#giftName").val();
							var giftType = $("#giftType").val();
							var giftStr = "";
							if(giftName !=null && giftName !="" && giftType !=null && giftType !="" ){
								giftStr = giftName+"@#"+giftType+"###";
							}
							if(giftCount >= 1){
								for ( var k = 0; k < giftCount; k++) {
									var giftName = $("#giftName"+k).val();
									var giftType = $("#giftType"+k).val();
									if (giftName != undefined
											&& giftName != null
											&& giftName != "") {
										giftStr = giftStr + giftName+"@#"+giftType+"###";
									}
								}
							}
							var radio = document.getElementsByName("isPrepaymentCard");
							var isPrepaymentCard = null;
							for ( var i = 0; i < radio.length; i++) {
								if (radio[i].checked == true) {
									isPrepaymentCard = radio[i].value;
									break;
								}
							}
							$
									.ajax({
										url : '${webcontext}/crmdp/dealer/meal/saveMeal',
										type : 'post',
										data : {
											'code' : $("#code").val(),
											'name' : $("#name").val(),
											'cardId' : $("#cardName").val(),
											'status' : $("#status").val(),
											'description' : $("#description")
													.val(),
											'isPrepaymentCard' : isPrepaymentCard,
											'numberSequence' : $(
													"#numberSequence").val(),
											'price' : $("#price").val(),
											'unitOfPeriod' : $("#unitOfPeriod")
													.val(),
											'validPeriod' : $("#validPeriod")
													.val(),
											'memberBenfit':$("#memberBenfit").val(),
											'dataStr' : dataStr,
											'giftStr':giftStr
										},
										success : function(data) {
											if (data.code == true) {
												jAlert(
														data.msg,
														"提示",
														function() {
															var temp="query";
															window.location = '${webcontext}/crmdp/dealer/meal/toQueryMeal?temp='+temp;
														});
											} else if (data.code == false) {
												jAlert(data.msg);
											}
										},
										error : function() {
											jAlert("服务器错误，请联系管理员");
										},
									});
						});
	});
	
	
	//计算所有的预计金额
	function sumPrepayAmount() {
		var sumPrepayAmount = $("#prepayAmount").val();
		if (row_count >= 1) {
			for ( var k = 0; k < row_count; k++) {
				var amount = $("#prepayAmount" + k).val();
				if (amount != undefined && amount != null && amount != "") {
					var prepayAmounts = $("#prepayAmount" + k).val();
					sumPrepayAmount = fmoney(parseFloat(sumPrepayAmount)
							+ parseFloat(prepayAmounts), 1);
					$("#prepayAmount" + k)
							.val(
									fmoney(parseFloat($("#prepayAmount" + k)
											.val()), 1));
					$("#onePrice" + k).val(
							fmoney(parseFloat($("#onePrice" + k).val()), 1));
				}
			}
		}
		$("#price").val(fmoney(parseFloat(sumPrepayAmount), 1));
		$("#prepayAmount").val(fmoney(parseFloat($("#prepayAmount").val()), 1));
		$("#onePrice").val(fmoney(parseFloat($("#onePrice").val()), 1));
	}
	
	
	//格式化金额，保留两位小数点
	function fmoney(s, n) {
		n = n > 0 && n <= 20 ? n : 2;
		s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
		var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
		t = "";
		for ( var i = 0; i < l.length; i++) {
			//t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
			t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
		}
		return t.split("").reverse().join("") + "." + r;
	}

	function changeNumberOfUse() {
		if (row_count >= 1) {
			for ( var k = 0; k < row_count; k++) {
				if ($("#numberOfUse" + k).val() == null
						|| $("#numberOfUse" + k).val() == "") {
					$("#numberOfUse" + k).val("0");
				}
				if ($("#onePrice" + k).val() == null
						|| $("#onePrice" + k).val() == "") {
					$("#onePrice" + k).val("0");
				}
				if ($("#prepayAmount" + k).val() == null
						|| $("#prepayAmount" + k).val() == "") {
					$("#prepayAmount" + k).val("0");
				}
			}
		}
	}

	//选中项目列表中的值，改变类型的值
	function changeTicketType(value) {
		<%if (ticketList != null) {%>
			<%for (int k = 0; k < ticketList.size(); k++) {
					Ticket ticket = (Ticket) ticketList.get(k);%>
				if (value == <%=ticket.getId()%>) {
					var type = '<%=ticket.getTicketType()%>';
					$("#ticketType").val(type);
			changePrepayAmount("prepayAmount",
<%=ticket.getId()%>
	);
		}
<%}%>
	
<%}%>
	}

	//自加行选中项目列表中的值，改变类型的值
	function changeTicketType2(value, id) {
		var num = id.substring(id.length - 1, id.length);
		if (!isNaN(num)) {
<%if (ticketList != null) {%>
	
<%for (int k = 0; k < ticketList.size(); k++) {
					Ticket ticket = (Ticket) ticketList.get(k);%>
	if (value ==
<%=ticket.getId()%>
	) {
				var type = '<%=ticket.getTicketType()%>';
				$("#ticketType" + num).val(type);

				changePrepayAmount("prepayAmount" + num,
<%=ticket.getId()%>
	);
			}
<%}%>
	
<%}%>
	}
	}

	//改变预付金额的值
	function changePrepayAmount(id, ticketId) {
		$.ajax({
			url : '${webcontext}/crmdp/dealer/meal/getTicKetLineInfo',
			type : 'post',
			data : {
				'ticketId' : ticketId
			},
			success : function(data) {
				if (data.code == true) {
					var prepayAmount = data.prepayAmount;
					var num = id.substring(id.length - 1, id.length);
					$("#" + id).val(prepayAmount);
					if (!isNaN(num)) {
						$("#onePrice" + num).val(prepayAmount);
					} else {
						$("#onePrice").val(prepayAmount);
					}
				} else if (data.code == false) {
					jAlert(data.msg, '提示', function() {
						$("#" + id).val(0);
						var num = id.substring(id.length - 1, id.length);
						if (!isNaN(num)) {
							$("#numberOfUse" + num).val(0);
							$("#onePrice" + num).val(0);
						} else {
							$("#numberOfUse").val(0);
							$("#onePrice").val(0);
						}
					});
				}
				;
			},
			error : function(data) {
				jAlert(data.msg, '提示');
			}
		});
	}

	//修改数量，改变预付金额的值
	function editPrepayAmount(id) {
		if (row_count >= 1) {
			var num = id.substring(id.length - 1, id.length);
			var sumAmount = "";
			if (!isNaN(num)) {
				var numberOfUse = $("#numberOfUse" + num).val();
				var onePrice = $("#onePrice" + num).val();
				sumAmount = parseFloat(numberOfUse) * parseFloat(onePrice);
				$("#prepayAmount" + num).val(sumAmount);
			} else {
				var numberOfUse = $("#numberOfUse").val();
				var onePrice = $("#onePrice").val();
				sumAmount = parseFloat(numberOfUse) * parseFloat(onePrice);
				$("#prepayAmount").val(sumAmount);
			}
		} else {
			var numberOfUse = $("#numberOfUse").val();
			var onePrice = $("#onePrice").val();
			sumAmount = parseFloat(numberOfUse) * parseFloat(onePrice);
			$("#prepayAmount").val(sumAmount);
		}
		sumPrepayAmount();
	}
	//删除行
	function deleteRow(id) {
		$("#" + id).parent().parent().remove();
	}

	//入会礼新增行
	function insertRow2() {
		var table = $("#gift_tabs2");
		var row = $("<tr></tr>");
		var td0 = $("<td></td>");
		var td1 = $("<td></td>");
		var td2 = $("<td></td>");
		td0
				.append($("<select id='giftName"
						+ giftCount
						+ "'  name='giftName' class='form-control input-sm' style='width: 220px;' onchange='changeType2(this[selectedIndex].value,this.id)'><option value='N/A'>--------请选择项目---------</option><core:forEach items='${resultList}' var='list'><option value='${list.id}'>${list.name}</option></core:forEach></select>"));
		row.append(td0);
		td1
				.append($("<input class='form-control input-sm' id='giftTypeText"
				+ giftCount
				+ "' type='text' readonly /> <input class='form-control input-sm hidden' id='giftType"
				+ giftCount
				+ "' type='text' readonly />"));
		row.append(td1);
		td2
				.append($("<button type='button' id='delete"
						+ giftCount
						+ "' class='btn btn-warning btn-sm' onclick='deleteRow(this.id)' style='margin-left: 10px;'>删除</button>"));
		row.append(td2);
		table.append(row);
		giftCount++;
	}

	function changeType(value) {
		<%if (resultList != null) {%>
			<%for (int k = 0; k < resultList.size(); k++) {
					ResultDto resultDto = (ResultDto) resultList.get(k);%>
				if (value == '<%=resultDto.getId()%>') {
					var typeText = '<%=resultDto.getTypeText()%>';
					var type = '<%=resultDto.getType()%>';
					$("#giftTypeText").val(typeText);
					$("#giftType").val(type);
				}
			<%}%>
		<%}%>
}
	
	//自加行选中项目列表中的值，改变类型的值
	function changeType2(value, id) {
		var num = id.substring(id.length - 1, id.length);
		if (!isNaN(num)) {
	<%if (resultList != null) {%>

	<%for (int k = 0; k < resultList.size(); k++) {
					ResultDto resultDto = (ResultDto) resultList.get(k);%>
	if (value =='<%=resultDto.getId()%>'
	) {
		var typeText = '<%=resultDto.getTypeText()%>';
		var type = '<%=resultDto.getType()%>';
				$("#giftTypeText" + num).val(typeText);
				$("#giftType" + num).val(type);
			}
<%}%>
	
<%}%>
	}
	}

	function checkCode() {
		$
				.ajax({
					url : '${webcontext}/crmdp/dealer/meal/checkCode',
					type : 'post',
					data : {
						'code' : $("#code").val()
					},
					success : function(data) {
						if (data.code == true) {
							jAlert(data.msg,"提示");
						} else if (data.code == false) {
							$("#codevli").addClass("has-error");
							$('#code_valierr').html(data.msg);
						}
					},
					error : function() {
						jAlert("服务器错误，请联系管理员","提示");
					},
				});
	}
</script>

<style>
.hr {
	text-align: center;
	width: 100%;
	background-color: #0071C1;
	height: 1px;
	margin-bottom: 10px;
}

.rowDiv {
	width: 90%;
}

.formDiv {
	float: left;
	width: 50%;
}

.textarea {
	width: 700px;
	height: 100px;
	max-width: 700px;
	max-height: 100px;
	resize: none;
}
</style>
<body>
	<div id="content">
		<div style="color: #025D7B; height: 26px; line-height: 26px;">
			<span>套餐定义</span> <span>&gt;</span> <span>套餐新增</span>
		</div>
		<div class="hr"></div>
		<form:form id="mealForm" action="" class="form-horizontal"
			method="post" modelAttribute="dto" role="form">
			<input type="hidden" name="qName" value="${name}">
			<input type="hidden" name="qCode" value="${code}">
			<input type="hidden" name="qStatus" value="${status}">
			<input type="hidden" id="currentPage" name="pager.currentPage" value="${currentPage}">
			<div class="row rowDiv">
				<div id="codevli" class="form-group formDiv has-feedback">
					<label class="col-sm-3 control-label" for="code">套餐编号</label>
					<div class="col-sm-6">
						<input class="form-control input-sm" id="code" name="code"
							type="text" check-type="required" required-message="请填写套餐编号"
							onblur="checkCode()" />
					</div>
					<span id="code_valierr" class="help-block"></span>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="name">套餐名称</label>
					<div class="col-sm-6">
						<input class="form-control input-sm" id="name" name="name"
							type="text" check-type="required" required-message="请填写套餐名称" />
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="cardName">卡片类型</label>
					<div class="col-sm-6">
						<select id="cardName" name="cardName"
							class="form-control input-sm">
							<core:forEach items="${cardList}" var="list">
								<option value="${list.id}">${list.name}</option>
							</core:forEach>
						</select>
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="status">状态</label>
					<div class="col-sm-6">
						<select id="status" name="status" class="form-control input-sm" disabled>
							<option value="0">未启用</option>
							<option value="1">有效</option>
							<option value="2">停用</option>
						</select>
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="description">说明</label>
					<div class="col-sm-7">
						<input class="form-control input-sm" id="description"
							name="description" type="text" check-type="required"
							required-message="请填写说明" />
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="isPrepaymentCard">是否预付费</label>
					<div class="col-sm-6">
						<label class="radio-inline"> <input type="radio"
							name="isPrepaymentCard" id="isPrepaymentCard1" value="1">是
						</label> <label class="radio-inline"> <input type="radio"
							name="isPrepaymentCard" id="isPrepaymentCard2" value="0" checked>否
						</label>
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="numberSequence">购买次数</label>
					<div class="col-sm-6">
						<input class="form-control input-sm text-right"
							id="numberSequence" name="numberSequence" type="text"
							check-type="number" required-message="请填写购买次数" value="0" />
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="price">建议零售价</label>
					<div class="col-sm-6">
						<input class="form-control input-sm text-right" id="price"
							name="price" value="0" readonly />
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="validPeriod">有效期</label>
					<div class="col-sm-3">
						<input class="form-control input-sm text-right" id="validPeriod"
							name="validPeriod" type="text" />
					</div>
					<div class="col-sm-3">
						<select id="unitOfPeriod" name="unitOfPeriod"
							class="form-control input-sm">
							<option value="Y">年</option>
							<option value="M">月</option>
							<option value="D">天</option>
						</select>
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="memberBenfit">会员福利</label>
					<div class="col-sm-3">
						<textarea class="form-control textarea" rows="3" id="memberBenfit"
							name="memberBenfit" maxLength="2000"></textarea>
					</div>
				</div>
			</div>
			<table id="data_tabs" class="table"
				style="margin-top: 20px; margin-left: 20px; width: 98%;">
				<thead>
					<tr>
						<th class="text-center">项目</th>
						<th class="text-center">类型</th>
						<th class="text-center">数量</th>
						<th class="text-center">单价</th>
						<th class="text-center">预付金额</th>
						<th class="text-center">操作</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td><select id="shortName" name="shortName"
							class="form-control input-sm" style="width: 220px;"
							onchange="changeTicketType(this[selectedIndex].value)">
								<option value="N/A">--------请选择项目---------</option>
								<core:forEach items="${ticketList}" var="list">
									<option value="${list.id}">${list.ticketName}</option>
								</core:forEach>
						</select></td>
						<td><input class="form-control input-sm" id="ticketType"
							type="text" readonly /></td>
						<td><input class="form-control input-sm text-right"
							id="numberOfUse" type="text" value="0"
							onchange="editPrepayAmount(this.id)" /></td>
						<td><input class="form-control input-sm text-right"
							id="onePrice" type="text" value="0" readonly /></td>
						<td><input class="form-control input-sm text-right"
							id="prepayAmount" type="text" value="0" readonly /></td>
					</tr>
				</tbody>
			</table>
			<div style="margin-left: 300px;">
				<button type="button" class="btn btn-success btn-sm" id="insertRow">
					<i class="glyphicon glyphicon-plus" style="color: #FFFFFF"></i>&nbsp;新增项目
				</button>
				<span id="msgInfo" class="text-danger"></span>
			</div>

			<table id="gift_tabs2" class="table"
				style="margin-top: 20px; margin-left: 20px; width: 60%;">
				<thead>
					<tr>
						<th class="text-center">项目</th>
						<th class="text-center">类型</th>
						<th class="text-center">操作</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td><select id="giftName" name="giftName"
							class="form-control input-sm" style="width: 220px;"
							onchange="changeType(this[selectedIndex].value)">
								<option value="N/A">--------请选择项目---------</option>
								<core:forEach items="${resultList}" var="list">
									<option value="${list.id}">${list.name}</option>
								</core:forEach>
						</select></td>
						<td><input class="form-control input-sm" id="giftTypeText"
							type="text" readonly /><input
							class="form-control input-sm hidden" id="giftType" type="text"
							readonly /></td>
					</tr>
				</tbody>
			</table>
			<div style="margin-left: 300px;">
				<button type="button" class="btn btn-success btn-sm" id="saveBtn">
					<i class="glyphicon glyphicon-floppy-saved" style="color: #FFFFFF"></i>&nbsp;保
					存
				</button>
				<button type="button" class="btn btn-success btn-sm"
					onclick="insertRow2()">
					<i class="glyphicon glyphicon-plus" style="color: #FFFFFF"></i>&nbsp;入会礼
				</button>
				<button type="button" class="btn btn-success btn-sm" id="returnBtn">
					<i class="glyphicon glyphicon-retweet" style="color: #FFFFFF"></i>&nbsp;返回
				</button>
				<span id="msgInfo" class="text-danger"></span>
			</div>
		</form:form>
	</div>
</body>
</html>